dojo.require("dijit.dijit"); // optimize: load dijit layer
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit.Toolbar");
dojo.require("dijit.form.ComboButton");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.Button");
dojo.require("dijit.MenuItem");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.Dialog");
dojo.require("dojo.parser"); // scan page for widgets

/* global variables */
// counter
var counter = 0;
var current_grid_item = null; // for workingDays and relations
var store_no_save = false;

dojo.addOnLoad( function()
{
	// edit workingDays
	var edit_workingDays = function(e){
		if (
			(this == grid_employee && e.cellIndex == 6)
			|| (this == grid_department && e.cellIndex == 2)
		) {
			current_grid_item = e.grid.getItem(e.rowIndex);
			var days = current_grid_item.workingDays;
			var bin = 1;
			for (var i=0; i<7; i++)
			{
				if ((days & bin) == bin)
				{
					dijit.byId("cb_wd_"+bin).attr("checked", true);
				} else
				{
					dijit.byId("cb_wd_"+bin).attr("checked", false);
				}
				bin = bin * 2;
			}
			
			if (current_grid_item.workingDays_inherit == 1)
			{
				dijit.byId('cb_wd_inherit').attr("checked", true);
			} else
			{
				dijit.byId('cb_wd_inherit').attr("checked", false);
			}
			inherit_workingDays(dijit.byId('cb_wd_inherit').attr("checked"));
			
			if (this == grid_department)
			{
				dojo.byId("dlg_inherit").style.display = 'none';
			} else
			{
				dojo.byId("dlg_inherit").style.display = 'block';
			}
			dialog_workingDays.show();
		}
		dojo.stopEvent(e);
	};
	dojo.connect(grid_employee, "onCellClick", grid_employee, edit_workingDays);
	dojo.connect(grid_department, "onCellClick", grid_department, edit_workingDays);
	
	dialog_wait.closeButtonNode.style.display = "none";

	setup_stores();
	
	// hide loading gif
	window.setTimeout(function()
	{
		document.getElementById('img').style.display='none';
		document.getElementById('form').style.visibility='';
	}, 100);
});

var get_inherited = function (field, rowIndex, item)
{
	if (item != null)
	{
		var x = store_department_employee.getValue(item, field);
		if (x == 0)
		{
			// inherit from department
			// search the parent
			var parent_field = null;
			store_department_employee.fetch({
				query: {id: 'dep_*'},
				onItem: function(itm, req)
				{
					var children = store_department_employee.getValues(itm, "children");
					var search = 'dnd_'+item.id+'_';
					for (var i=0; i<children.length; i++)
					{
						var id = '' + children[i].id; // string
						if (id.substr(0, search.length) == search)
						{
							// parent found
							parent_field = store_department_employee.getValue(children[i], field);
							break;
						}
					}
					return req;
				}
			});
			return parent_field;
		}
		return x;
	}
};

var filter_employees = function (dep)
{
	if (dep=='')
	{
		grid_employee.setQuery({ });
	} else
	{
		// dep must be a string
		grid_employee.setQuery({departmentID:''+dep});
	}
};

var refresh_all = function ()
{
	try {
		grid_employee.store.close();
	} catch (e) {
		grid_employee.store.revert();
		refresh_all();
		return;
	}
	
	grid_employee.sort();
	grid_department.sort();
};

var setup_stores = function()
{
	store_customer._saveEverything = function(saveCompleteCallback, saveFailedCallback, newFileContentString) {
		dialog_wait.show();
	    dojo.xhrPost({
	        url: "html?mdl=admin&action=write&tbl=customer",
	        content: { data: newFileContentString },
	        handleAs: "text",
	        timeout: 20000,
		    load: function(rdata){
				if (rdata != 'null')
				{
					alert ("Error while saving data. Please try again later. ("+rdata+")");
				}
				dialog_wait.hide();
				if (typeof saveCompleteCallback == 'function')
				{
					saveCompleteCallback();
				}
	        },
	        error: saveFailedCallback
	    });
	};

	store_department_employee._saveEverything = function(saveCompleteCallback, saveFailedCallback, newFileContentString) {
		dialog_wait.show();
	    dojo.xhrPost({
	        url: "html?mdl=admin&action=write&tbl=department_employee",
	        content: { data: newFileContentString },
	        handleAs: "text",
	        timeout: 20000,
		    load: function(rdata){
				if (rdata != 'null')
				{
					alert ("Error while saving data. Please try again later. ("+rdata+")");
				}
				dialog_wait.hide();
				if (typeof saveCompleteCallback == 'function')
				{
					saveCompleteCallback();
				}
	        },
	        error: function()
	        {
	        	if (typeof saveFailedCallback == 'function')
				{
	        		saveFailedCallback();
				}
	        }
	    });
	};
	
	dojo.connect(store_customer, 'onSet', store_customer, function(item, attribute, old, new_)
	{
		// check if something was changed
		if (
			old != new_
			&& store_no_save == false
		) {
			var wrong = false;
			if (attribute == 'systemAccount')
			{
				if (!new_.match(/^(.+)@(.{2,})\.(.{2,4})$/i))
				{
					wrong = true;
				}
			}
			if (!wrong)
			{
				wrong = !(check_customer_settings(
					store_customer.getValue(item, 'systemAccount')
					, store_customer.getValue(item, 'password')
				));
				alert ("Check of credentials for google calendar service was failed.");
			}
			if (wrong)
			{
				// wrong input
				window.setTimeout( function()
				{
					store_no_save = true;
					store_customer.setValue(item, attribute, old);
					store_no_save = false;
				}, 5);
			} else
			{
				window.setTimeout( function()
				{
					store_customer.save();
				}, 5);
			}
		}
	});

	dojo.connect(store_department_employee, 'onSet', store_department_employee, function(item, attribute, old, new_)
	{
		if (old == current_employee_account && attribute == 'label')
		{
			// own account cannot be changed
			// wrong input
			window.setTimeout( function()
			{
				store_no_save = true;
				store_department_employee.setValue(item, attribute, old);
				store_no_save = false;
			}, 5);
			return;	
		}
		
		if (this.getValue(item, 'id') == 'emp_X')
		{
			// change relations if label changed
			if (attribute == "label" && old != new_)
			{
				if (!store_no_save)
				{
					store_no_save = true;
					store_department_employee.fetch({
						sync: true,
						query: {id:'dep_*'},
						onItem: function(itm)
						{
							var id = store_department_employee.getValue(itm, 'id');
							var children = store_department_employee.getValues(itm, 'children');
							for (var i=0; i<children.length; i++)
							{
								if (store_department_employee.getValue(children[i], 'label') == old)
								{
									store_department_employee.setValue(children[i], 'label', new_);
								}
							}
						}
					});
					store_no_save = false;
				}
			}
			return;
		} else if (this.getValue(item, 'id') == 'dep_X')
		{
			return;
		}
		
		// check if something was changed
		if (
			old != new_
			&& store_no_save == false
		) {
			if (check_changes(item, attribute, new_))
			{
				window.setTimeout( function()
				{
					store_department_employee.save();
				}, 5);
			} else
			{
				// wrong input
				window.setTimeout( function()
				{
					store_no_save = true;
					store_department_employee.setValue(item, attribute, old);
					store_no_save = false;
				}, 5);
			}
		}
	});
};

var check_changes = function(item, key, value)
{
	var id = store_department_employee.getValue(item, 'id');
	value = ''+value; // cast to string
	if (id.match(/^emp_/))
	{
		if (key == 'label')
		{
			if (value.match(/^(.+)@(.{2,})\.(.{2,4})$/i))
			{
				return true;
			} else
			{
				return false;
			}
		} else if (key == 'givenName' || key == 'lastName')
		{
			if (value == '') return false;
			else return true;
		} else if (
			key == 'entitlementLeave'
			|| key == 'specialLeave'
			|| key == 'remainingLeave'
			|| key == 'remainingLeavePrevYear'
		) {
			return !( value.match(/[^0-9.]/) );

		}
	} else if (id.match(/^dep_/))
	{
		if (key == 'label')
		{
			return value != '';
		} else if (key == 'holidayCal')
		{
			// check for readable ics file
			var r = false;
			dojo.xhrGet({
				url: "html?action=check_ics&mdl=admin",
				content: {
					'url': value
				},
				sync: true,
				handleAs: "text",
				load: function(rdata, ioArgs) {
					if (rdata == 'false')
					{
						r = false;
						alert("The ICS-file isn't readable. Make sure the URL is correct.");
					} else if (rdata == 'true')
					{
						r = true;
					} else
					{
						alert ("Error while checking data. Please try again later. ("+rdata+")");
					}
			        return rdata;
			    },
			    error: function(response, ioArgs) {
			    	alert ("Error while checking data. Please try again later. ("+arguments[0]+")");
			        return response;
			    }
			});
			return r;
		}
	}
	return true;
};

var check_new_department = function()
{
	var v = dijit.byId('td_dep_name').attr('value');
	if (v == '')
	{
		dijit.byId('td_dep_name').domNode.style.border = '2px solid red';
		return false;
	} else
	{
		// check for duplicates
		var dup = false;
		store_department_employee.fetch({
			query: {id: 'dep_*', label: v},
			sync: true,
			onItem: function(i) {
				dup = true;
			}
		});
		if (dup)
		{
			alert("Duplicate detected!");
			return false;
		}
		dijit.byId('td_dep_name').domNode.style.border = '1px solid #B3B3B3';
		return true;
	}
};

var check_new_employee = function()
{
	var label = dijit.byId('td_emp_account').attr('value');
	if (!label.match(/^(.+)@(.{2,})\.(.{2,4})$/i))
	{
		dijit.byId('td_emp_account').domNode.style.border = '2px solid red';
	} else
	{
		dijit.byId('td_emp_account').domNode.style.border = '1px solid #B3B3B3';
	}
	
	var gname = dijit.byId('td_emp_gname').attr('value');
	if (gname == '')
	{
		dijit.byId('td_emp_gname').domNode.style.border = '2px solid red';
	} else
	{
		dijit.byId('td_emp_gname').domNode.style.border = '1px solid #B3B3B3';
	}
	
	var lname = dijit.byId('td_emp_lname').attr('value');
	if (lname == '')
	{
		dijit.byId('td_emp_lname').domNode.style.border = '2px solid red';
	} else
	{
		dijit.byId('td_emp_lname').domNode.style.border = '1px solid #B3B3B3';
	}

	return check_new_employee_fields(label, gname, lname);
};

var check_new_employee_fields = function(label, gname, lname, duplicate)
{
	if (label.match(/^(.+)@(.{2,})\.(.{2,4})$/i)
		&& gname != ''
		&& lname != ''
	) {
		// check for duplicates
		
		var dup = false;
		var nDup = 0;
		if (typeof (duplicate) && duplicate > 0)
		{
			nDup = duplicate;
		}
		store_department_employee.fetch({
			query: {id: 'emp_*', label: label},
			sync: true,
			onItem: function(i) {
				if (nDup > 0)
				{
					nDup--;
				} else
				{
					dup = true;
				}
			}
		});
		
		if (typeof (duplicate) && duplicate > 0)
		{
			nDup = duplicate;
		}
		store_department_employee.fetch({
			query: {id: 'emp_*', givenName:gname, lastName:lname},
			sync: true,
			onItem: function(i) {
				if (nDup > 0)
				{
					nDup--;
				} else
				{
					dup = true;
				}
			}
		});
		if (dup)
		{
			alert("Duplicate detected!");
			return false;
		}
		return true;
	} else
	{
		return false;
	}
};

var inherit_workingDays = function(chk)
{
	var bin = 1;
	for (var i=0; i<7; i++)
	{
		if (chk)
		{
			dijit.byId("cb_wd_"+bin).attr("disabled", true);
		} else
		{
			dijit.byId("cb_wd_"+bin).attr("disabled", false);
		}
		bin = bin * 2;
	}
	dijit.byId("cb_wd_inherit").attr("disabled", false);
};

var apply_workingDays = function()
{
	var dez = 0;
	
	var bin = 1;
	for (var i=0; i<7; i++)
	{
		if (dijit.byId("cb_wd_"+bin).attr("checked") == true)
		{
			dez = dez | bin;
		}
		
		bin = bin * 2;
	}
	
	var wd_i = store_department_employee.getValue(current_grid_item, "workingDays_inherit");
	var wd =  store_department_employee.getValue(current_grid_item, "workingDays");

	var wd_i_n;
	var wd_n = dez;
	
	if (dijit.byId('cb_wd_inherit').attr('checked') == false)
	{
		wd_i_n = 0;
	} else
	{
		// inherit
		wd_i_n = 1;
	}
	if (wd_i_n != wd_i || wd_n != wd)
	{
		// changes
		store_no_save = true;
		store_department_employee.setValue(current_grid_item, "workingDays_inherit", wd_i_n);
		store_department_employee.setValue(current_grid_item, "workingDays", wd_n);
		store_no_save = false;
		
		if (
			store_department_employee.getValue(current_grid_item, 'id') != 'emp_X'
			&& store_department_employee.getValue(current_grid_item, 'id') != 'dep_X'
		) {
			store_department_employee.save();
		}
	}
	
	dialog_workingDays.hide();
};

var format_pwd = function (plain)
{
	return '******';
};

var format_workingDays = function (plain)
{
	var days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
	var bin = 1;
	var text = '';
	for (var i=0; i<7; i++)
	{
		if ((plain & bin) == bin)
		{
			text+= '<span style="font-weight:bolder !important;">'+days[i]+ '</span>-';
		} else
		{
			text+= days[i]+ '-';
		}
		bin = bin * 2;
	}
	return '<button class="btn_workingDays">'+text.substring(0, text.length-1)+'</button>';
};

var format_admin = function(plain)
{
	if (plain == "false" || plain == 0 || plain == '')
	{
		return '<input type="checkbox" />';
	} else
	{
		return '<input type="checkbox" checked="checked" />';
	}
};

var format_options_emp_delete = function(st)
{
	var r ='';
	var itm = grid_employee.getItem(arguments[1]);
	if (store_department_employee.getValue(itm, "id") == "emp_X")
	{
		r += '<img class="btn" src="modules/admin/img/add.png" onClick="insert_new_employee(grid_employee.getItem('+arguments[1]+'))"/>';
	} else
	{
		r += '<img class="btn" src="modules/admin/img/delete.gif" onClick="delete_employee('+arguments[1]+')"/>';
	}
	return r;
};

var format_options_emp_relations = function(st)
{
	var r ='';
	r += '<button class="btn_workingDays" onClick="edit_reference(grid_employee.getItem('+arguments[1]+'))">Set relations</button>';
	return r;
};

var format_options_dep = function(st)
{
	var r ='';
	if (st == "dep_X")
	{
		r += '<img class="btn" src="modules/admin/img/add.png" onClick="insert_new_department(grid_department.getItem('+arguments[1]+'))"/>';
	} else
	{
		r += '<img title="show employees" alt="show employees" class="btn" src="modules/admin/img/filter.gif" onClick="show_employees_from_department('+arguments[1]+')"/>';
		r += '&nbsp;<img class="btn" src="modules/admin/img/delete.gif" onClick="delete_department('+arguments[1]+')"/>';
	}
	return r;
};

var format_number = function(plain)
{
	plain = ''+plain;  // convert to string
	if (plain.indexOf('.') == -1)
	{
		plain+='.0';
	}
	return '<div style="text-align:right;">'+ plain +'</div>';
};

var delete_employee = function(rowIndex)
{
	var itm = grid_employee.getItem(rowIndex);
	if (current_employee_account == store_department_employee.getValue(itm, 'label'))
	{
		// own employee cannot be deleted
		alert("You cannot delete yourself.");
		return;
	}
	
	grid_employee.store.deleteItem(itm);
	store_department_employee.save({
		onComplete: function(){
			refresh_all();
		}
	});
};

var delete_department = function(rowIndex)
{
	var itm = grid_department.getItem(rowIndex);
	grid_department.store.deleteItem(itm);
	store_department_employee.save({
		onComplete: function(){
			refresh_all();
		}
	});
	show_employees_from_department(-1);
};

var edit_reference = function(eitm)
{
	current_grid_item = eitm;
	
	var tbl = dojo.byId('dialog_relations_tbody');
	// empty table
	while (tbl.rows.length > 1)
	{
		tbl.deleteRow(1);
	}
	store_department_employee.fetch({
		query: {id:'dep_*'},
		onItem: function(itm)
		{
			var id = store_department_employee.getValue(itm, 'id');
			if (id=='dep_X') return;
			
			var children = store_department_employee.getValues(itm, 'children');
			var role = '';
			for (var i=0; i<children.length; i++)
			{
				if (store_department_employee.getValue(children[i], 'label') == store_department_employee.getValue(eitm, 'label'))
				{
					role = store_department_employee.getValue(children[i], 'role');
				}
			}
			var num = tbl.rows.length;
			
			var row = tbl.insertRow(num);
			var cell1 = row.insertCell(0);
			cell1.innerHTML = store_department_employee.getValue(itm, 'label');
			
			var cb1 = document.createElement("input");
			cb1.setAttribute("type", "checkbox");
			cb1.setAttribute("id", "rel_m_"+ num);
			cb1.setAttribute("value", id);
			var cell2 = row.insertCell(1);
			cell2.appendChild(cb1);
			if (role != '')
			{
				cb1.checked = 'checked';
			}
			
			var cb2 = document.createElement("input");
			cb2.setAttribute("type", "checkbox");
			cb2.setAttribute("id", "rel_s_"+ num);
			cb2.setAttribute("value", id);
			var cell3 = row.insertCell(2);
			cell3.appendChild(cb2);
			if (role == 'supervisor')
			{
				cb2.checked = 'checked';
			}

			dojo.connect(cb1, 'onclick', cb1, function()
			{
				if (!this.checked)
				{
					cb2.checked = '';
				}
			});
			dojo.connect(cb2, 'onclick', cb2, function()
			{
				if (this.checked)
				{
					cb1.checked = 'checked';
				}
			});
		},
		onComplete: function()
		{
			dialog_relations.show();
		}
	});
};

var show_employees_from_department = function(rowIndex)
{
	if (rowIndex == -1)
	{
		grid_employee.setQuery({
			departments:'*'
		});
		grid_employee.sort();
		dojo.byId('info_filter').style.display = 'none';
	} else
	{
		var itm = grid_department.getItem(rowIndex);
		var depID = store_department_employee.getValue(itm, "id");
		grid_employee.setQuery({
			departments:'*,'+depID+',*'
		});
		grid_employee.sort();
		tab_dep_emp.selectChild(cp_employee);
		dojo.byId('info_filter_dep').innerHTML = store_department_employee.getValue(itm, "label");
		dojo.byId('info_filter').style.display = 'block';
	}
};

var check_customer_settings = function(username, pwd)
{
	var r = false;
	dojo.xhrGet({
		url: "html?action=check&mdl=register",
		content: {
			'systemAccount': username,
			'pwd': pwd
		},
		sync: true,
		handleAs: "text",
		load: function(rdata, ioArgs) {
			if (rdata == 'false')
			{
				r = false;
			} else if (rdata == 'true')
			{
				r = true;
			} else
			{
				alert ("Error while saving data. Please try again later. ("+rdata+")");
			}
	        return rdata;
	    },
	    error: function(response, ioArgs) {
	    	alert ("Error while saving data. Please try again later. ("+arguments[0]+")");
	        return response;
	    }
	});
	
	return r;
};

/**
 * insert directly in grid
 */
var insert_new_employee = function (item)
{
	if (check_new_employee_fields(
			store_department_employee.getValue(item, "label")
			, store_department_employee.getValue(item, "givenName")
			, store_department_employee.getValue(item, "lastName")
			, 1
		)
	) {
		if (!check_relations(item))
		{
			alert(text_least_one_relation);
			return;
		}
		var new_id = 'emp_n'+(counter++);
		var attr_keys = store_department_employee.getAttributes(item);
		var attr_map = {};
		for (var i=0; i<attr_keys.length; i++)
		{
			attr_map[attr_keys[i]] = store_department_employee.getValue(item, attr_keys[i]);
		}
		attr_map.id = new_id;
		attr_map.account = attr_map.label;
		
		store_no_save = true;
		store_department_employee.setValue(item, 'label', text_new_employee);
		store_department_employee.setValue(item, 'givenName', '');
		store_department_employee.setValue(item, 'lastName', '');
		store_no_save = false;
		
		var new_item = store_department_employee.newItem(attr_map);
		store_department_employee.save({
			sync: true,
			onComplete: function()
			{
				refresh_all();
			}
		});
	} else
	{
		alert (text_wrong_input);
	}
};

var insert_new_department = function(item)
{
	if (
		store_department_employee.getValue(item, "label") != ""
		&& store_department_employee.getValue(item, "label") != text_new_department
	) {
		var new_id = 'dep_n'+(counter++);
		var attr_keys = store_department_employee.getAttributes(item);
		var attr_map = {};
		for (var i=0; i<attr_keys.length; i++)
		{
			attr_map[attr_keys[i]] = store_department_employee.getValue(item, attr_keys[i]);
		}
		attr_map.id = new_id;
		attr_map.name = attr_map.label;
		
		store_no_save = true;
		store_department_employee.setValue(item, 'label', text_new_department);
		store_department_employee.setValue(item, 'workingDays', '31');
		store_department_employee.setValue(item, 'holidayCal', '');
		store_no_save = false;
		
		var new_item = store_department_employee.newItem(attr_map);
		store_department_employee.save({
			sync: true,
			onComplete: function()
			{
				refresh_all();
			}
		});
	} else
	{
		alert ("Wrong input values.");
	}
};

var check_relations = function(item)
{
	var r = false;
	var label = store_department_employee.getValue(item, 'label');
	store_department_employee.fetch({
		sync: true,
		query: {id:'dep_*'},
		onItem: function(itm)
		{
			var children = store_department_employee.getValues(itm, 'children');
			for (var i=0; i<children.length; i++)
			{
				if (store_department_employee.getValue(children[i], 'label') == label)
				{
					r=true;
				}
			}
		}
	});
	return r;
};

var apply_relations = function()
{
	var i=1;
	store_no_save = true;
	var changes = false;
	var no_relations = true;
	while (dojo.byId('rel_s_'+i))
	{
		store_department_employee.fetchItemByIdentity({
			identity: dojo.byId('rel_s_'+i).value,
			sync: true,
			onItem: function(itm)
			{
				var role = '';
				if (dojo.byId('rel_s_'+i).checked)
				{
					role = 'supervisor';
				} else if (dojo.byId('rel_m_'+i).checked)
				{
					role = 'member';
				}
				if (role != '' && no_relations)
				{
					no_relations = false;
				}
				// delete old relation
				var emp_label = store_department_employee.getValue(current_grid_item, 'label');
				var children = store_department_employee.getValues(itm, 'children');
				var must_add = true;
				for (var ii=0; ii<children.length; ii++)
				{
					if (store_department_employee.getValue(children[ii], 'label') == emp_label)
					{
						// if no role, delete
						if (role == '')
						{
							store_department_employee.deleteItem(children[ii]);
							changes = true;
						} else
						{
							// else, update if needed
							if (store_department_employee.getValue(children[ii], 'role') != role)
							{
								store_department_employee.setValue(children[ii], 'role', role);
								changes = true;
							}
						}
						must_add = false;
					}
				}
				if (role != '' && must_add)
				{
					children = store_department_employee.getValues(itm, 'children');
					children.push(
						store_department_employee.newItem({
							id: 'rel_emp_js'+(counter++),
							label: emp_label,
							role: role
						})
					);
					store_department_employee.setValues(itm, 'children', children);
					grid_employee.sort();
					changes = true;
				}
			}
		});
		i++;
	}
	store_no_save = false;
	if (no_relations)
	{
		alert("There must be at least one relation.");
		/*var x = new dijit.Dialog({title:"Warning", content: });
		dojo.body().appendChild(x.domNode);
		x.startup();
		x.show();
		*/
	} else
	{
		if (changes && store_department_employee.getValue(current_grid_item, 'id')!='emp_X')
		{
			store_department_employee.save({
				sync: true,
				onComplete: function()
				{
					refresh_all();
				}
			});
		}
		dialog_relations.hide();
	}
};
